const router = require('koa-router')()
router.prefix('/mr')
const service = require('../services/es.service')
const cfg = require('../config')
const db = require('../services/db.service')
function loadStore() {
    delete require.cache[require.resolve('../store')]
    return require('../store')
}
function parseUrl(url) {

    let obj = {}
    let ind = url.indexOf('?')
    let u = decodeURI(url.substring(ind + 1))
    let arr = u.split('&')

    arr.forEach((e, i) => {
        let nameseperatepos = e.indexOf('=')
        let name = e.substr(0, nameseperatepos)
        let value = e.substr(nameseperatepos + 1, e.length - nameseperatepos - 1)
        obj[name] = (value)
    });

    return obj
}
//test
router.get('/test/', async (ctx, next) => {
    let p = parseUrl(ctx.request.url)
    console.log("parse finished");
    console.log(p);
    let confa = loadStore()
    try {

        ctx.body = {
            title: 'Success!',
            body: confa.testString
        }
    } catch (err) {
        console.log(err);
    }
})
//full test query
router.get('/', async (ctx, next) => {
    let p = parseUrl(ctx.request.url)
    if (cfg.authorization && (p['operatorID'] === undefined || p['operatorID'] === '')) {
        ctx.body = {
            title: 'Faild!',
            body: 'missing operator info'
        }
        return
    }
    console.log("parse finished");
    console.log(p);
    try {
        var r = await service.simplesearch(cfg.index, JSON.parse(p['conditions']), undefined, p['from'], p['size'], p['sort'])
        if (cfg.trace) {
            db.saveTrace(p['operatorID'], "simplesearch", r.spend, r.results.length, ctx.request.url)
        }
        ctx.body = {
            title: 'Success!',
            body: r
        }
        console.log('finished');
    } catch (err) {
        ctx.body = {
            title: 'Faild!',
            body: err
        }
        console.log(err);
    }
})


//condition search, should use keyword for text field
router.post('/search/', async (ctx, next) => {
    //let request = ctx.request
    let p = ctx.request.body
    if (cfg.authorization && (p['operatorID'] === undefined || p['operatorID'] === '')) {
        ctx.body = {
            title: 'Faild!',
            body: 'missing operator info'
        }
        return
    }
    //console.log(ctx.request.url);
    //console.log(postParam);
    //let p = parseUrl(postParam)
    // console.log("parse finished");
    // console.log(p);
    let query = JSON.parse(p['query'])
    console.log(query);
    try {
        // let isMridMode = false
        // if (query['parameter'] != undefined && query['parameter']['isMridMode'] != undefined)
        //     isMridMode = query['parameter']['isMridMode']
        // let distinctMrid = false
        // if (query['parameter'] != undefined && query['parameter']['distinctMrid'] != undefined)
        //     distinctMrid = query['parameter']['distinctMrid']
        let parameter = query['parameter']
        var r = await service.conditionsearch(cfg.index, query['conditionpipe'], query['showColumn'], p['from'], p['size'], p['sort'], parameter)
        if (cfg.trace) {
            db.saveTrace(p['operatorID'], "search", r.spend, r.results.length, cfg.codeSingleQuote(JSON.stringify(p)))
        }
        ctx.body = {
            title: 'Success!',
            body: r
        }
        console.log('finished');
    } catch (err) {
        ctx.body = {
            title: 'Faild!',
            body: err
        }
        console.log(err);
    }
})
router.post('/aggregate/', async (ctx, next) => {
    let p = ctx.request.body
    if (cfg.authorization && (p['operatorID'] === undefined || p['operatorID'] === '')) {
        ctx.body = {
            title: 'Faild!',
            body: 'missing operator info'
        }
        return
    }
    //console.log(ctx.request.url);

    // let p = parseUrl(ctx.request.url)
    // console.log("parse finished");
    // console.log(p);
    let aggrigate = JSON.parse(p['aggregattion'])
    let parameter = aggrigate['parameter']
    try {

        var r = await service.aggrigate(cfg.index, aggrigate, parameter)
        if (cfg.trace) {
            db.saveTrace(p['operatorID'], "aggregate", r.spends, r.statisticResult.length, cfg.codeSingleQuote(JSON.stringify(p)))
        }
        ctx.body = {
            title: 'Success!',
            body: r
        }
        console.log('finished');
    } catch (err) {
        ctx.body = {
            title: 'Faild!',
            body: err
        }
        console.log(err);
    }
})
module.exports = router